<template>
  <div class="departments">
    <el-card>
      <template #header>
        <div>组织架构</div>
      </template>
      <div class="tree">
        <!--  -->
        <TreeItem :item="topInfo" />
        <hr>
        <el-tree :data="list" :props="{ children: 'children' }">
          <template v-slot="{ data }">
            <!--  -->
            <TreeItem style="width: 100%" :item="data" @getData="getData" />
          </template>
        </el-tree>
      </div>
    </el-card>
    <!-- 弹窗组件
           bus传值
       1：Vue.prototype.$bus=new Vue()
       2:监听
          this.$bus.$on('事件名',(参数)=>{...})
       3:触发
         this.$bus.$emit('事件名',实参)
       4：销毁
       this.$bus.$off('事件名')

    -->
    <DialogItem ref="dialogItem" :init-list="initList" @getData="getData" />
  </div>
</template>
<script>
import TreeItem from './components/tree-item.vue'
import { companyDepartment } from '@/api/departments.js'
import DialogItem from '@/views/departments/components/dialogItem'
export default {
  components: {
    TreeItem,
    DialogItem
  },
  data() {
    return {
      topInfo: {
        name: '传智',
        manager: '负责人',
        isTop: true,
        id: '' // 确定当前点击项的pid
      },
      list: [],
      initList: [] // 原始组织架构数据
    }
  },
  created() {
    this.getData()
  },
  methods: {
    // 获取组织架构列表数据
    async getData() {
      const res = await companyDepartment()
      this.topInfo.name = res.data.companyName
      this.initList = res.data.depts // 存储原始列表数据
      this.list = this.changeData(res.data.depts, '')
      console.log('组织架构：', this.list)
    },
    // 将数据转换成树形数据结构
    changeData(arr, str = '') {
      return arr.filter((item) => {
        if (item.pid === str) {
          item.children = this.changeData(arr, item.id)
          return true
        }
      })
    }
  }
}
</script>
<style lang="scss" scoped>
.departments {
  padding: 30px;
  .tree {
    width: 80%;
    margin: 0 auto;
  }
}
</style>
